import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart';

import 'date_picker_title_widget.dart';

/// DateTimePicker widget. Can display date and time picker.
/// 基于这个代码改造的单轮滑动器flutter_cupertino_datetime_picker: ^3.0.0
///
class MySinglePickerWidget extends StatefulWidget {
  final DateTimePickerTheme pickerTheme;
  final int minuteDivider;
  final List<String> valueRange;
  int initItem = 0;

  var currentValue;

  late Function(String nowValue) valueChange;

  MySinglePickerWidget(
      {Key? key,
      required this.valueRange,
      this.pickerTheme = DateTimePickerTheme.Default,
      this.minuteDivider = 1,
      this.initItem = 0,
      required this.valueChange })
      : super(key: key) {

    currentValue=valueRange[initItem];

  }

  @override
  State<StatefulWidget> createState() => _MySinglePickerWidgetState(this.minuteDivider, this.valueRange, this.initItem,this.valueChange);
}

class _MySinglePickerWidgetState extends State<MySinglePickerWidget> {
  late int _minuteDivider;
  late FixedExtentScrollController scrollController;
  late List<String>? valueRange;
  late Map<String, List<String>> _valueRangeMap = Map();
  late Function(String nowValue) valueChange;

  _MySinglePickerWidgetState(int this._minuteDivider, List<String> this.valueRange, int initialItem,this.valueChange) {
    scrollController = FixedExtentScrollController(initialItem: initialItem);
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Material(color: Colors.transparent, child: _renderPickerView(context)),
    );
  }

  /// render time picker widgets
  Widget _renderPickerView(BuildContext context) {
    Widget pickerWidget = _renderDatePickerWidget();

    // display the title widget
    if (widget.pickerTheme.title != null || widget.pickerTheme.showTitle) {
      Widget titleWidget = DatePickerTitleWidget(
        pickerTheme: widget.pickerTheme,
        onCancel: () => _onPressedCancel(),
        onConfirm: () => _onPressedConfirm(),
        locale: DateTimePickerLocale.en_us,
      );
      return Column(children: <Widget>[titleWidget, pickerWidget]);
    }
    return pickerWidget;
  }

  /// pressed cancel widget
  void _onPressedCancel() {
    // widget.onCancel?.call();

    Navigator.pop(context);
  }

  /// pressed confirm widget
  void _onPressedConfirm() {
    // if (widget.onConfirm != null) {
    //   DateTime dateTime = DateTime(_currYear, _currMonth, _currDay, _currHour, _currMinute, _currSecond);
    //   widget.onConfirm!(dateTime, _calcSelectIndexList());
    // }
    Navigator.pop(context);
  }

  /// notify selected datetime changed
  void _onSelectedChange() {
    // if (widget.onChange != null) {
    //   DateTime dateTime = DateTime(_currYear, _currMonth, _currDay, _currHour, _currMinute, _currSecond);
    //   widget.onChange!(dateTime, _calcSelectIndexList());
    // }
  }

  /// find scroll controller by specified format
  FixedExtentScrollController _findScrollCtrl(String format) {
    return scrollController!;
  }

  /// find item value range by specified format
  List<String> _findPickerItemRange(String format) {
    _valueRangeMap.forEach((key, value) {
      if (format.contains(key)) {
        valueRange = value;
      }
    });
    if (valueRange == null) {
      throw Exception('Illegal format $format');
    }
    return valueRange!;
  }

  /// render the picker widget of year、month and day
  Widget _renderDatePickerWidget() {
    List<Widget> pickers = [];
    List<String> formatArr = List.of(["y"]);

    formatArr.forEach((format) {
      List<String> valueRange = _findPickerItemRange(format);
      Widget pickerColumn = _renderDatePickerColumnComponent(
        scrollCtrl: scrollController,
        valueRange: valueRange,
        format: format,
        minuteDivider: widget.minuteDivider,
        valueChanged: (value) {
          this.valueChange(valueRange[value]);
          //debugPrint("valueChanged--- ${valueRange[value]} type-> ${valueRange[value].runtimeType}");
          widget.currentValue=valueRange[value];
        },
      );
      pickers.add(pickerColumn);
    });
    return Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: pickers);
  }

  Widget _renderDatePickerColumnComponent({
    required FixedExtentScrollController scrollCtrl,
    required List<String> valueRange,
    required String format,
    required ValueChanged<int> valueChanged,
    required int minuteDivider,
  }) {
    IndexedWidgetBuilder builder = (context, index) {
      String value = valueRange[index].toString();
      return _renderDatePickerItemComponent(value, format);
    };

    Widget columnWidget = Container(
      padding: EdgeInsets.all(8.0),
      width: double.infinity,
      height: widget.pickerTheme.pickerHeight,
      decoration: BoxDecoration(color: widget.pickerTheme.backgroundColor),
      child: CupertinoPicker.builder(
        backgroundColor: widget.pickerTheme.backgroundColor,
        scrollController: scrollCtrl,
        selectionOverlay: widget.pickerTheme.selectionOverlay ??
            Container(
              decoration: BoxDecoration(
                border: Border.symmetric(
                  horizontal: BorderSide(color: Colors.black26),
                ),
              ),
            ),
        itemExtent: widget.pickerTheme.itemHeight,
        onSelectedItemChanged: valueChanged,
        childCount: valueRange.length,
        itemBuilder: builder,
      ),
    );
    return Expanded(
      flex: 1,
      child: columnWidget,
    );
  }

  /// render hour、minute、second picker item
  Widget _renderDatePickerItemComponent(String value, String format) {
    return Container(
      height: widget.pickerTheme.itemHeight,
      alignment: Alignment.center,
      child: Text(
        value,
        style: widget.pickerTheme.itemTextStyle,
      ),
    );
  }
}
